package com.zwj.design.behavior.observer.demo2;

import com.zwj.design.behavior.observer.demo1.DisplayElement;
import lombok.Data;

import java.util.Observable;
import java.util.Observer;

/**
 * 实现JDK中的Observer接口，声明为观察者
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/3/18 23:05
 */
@Data
public class CurrentConditionsDisplay implements Observer, DisplayElement {
    /**
     * 温度
     */
    private float temperature;
    /**
     * 湿度
     */
    private float humidity;
    /**
     * 压强
     */
    private float pressure;
    /**
     * 主题
     */
    private Observable observable;

    /**
     * 将当前类注册为观察者
     *
     * @param observable 主题
     */
    public CurrentConditionsDisplay(Observable observable) {
        this.observable = observable;
        observable.addObserver(this);
    }

    @Override
    public void display() {
        System.err.println("当前温度：" + temperature + "℃，当前湿度与压强为：" + humidity + "%," + pressure);
    }

    @Override
    public void update(Observable obs, Object arg) {
        //如果观察者为WeatherData，则观察者做更新操作
        if (obs instanceof WeatherData) {
            WeatherData weatherData = (WeatherData) obs;
            this.temperature = weatherData.getTemperature();
            this.humidity = weatherData.getHumidity();
            this.pressure = weatherData.getPressure();
        }
    }
}
